import React, { useState } from 'react'
import style from '@/pages/index.less'
import { Upload } from 'antd'
import { getBase64, beforeUpload } from '@/utils/upload'
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface'
import type { UploadChangeParam } from 'antd/es/upload'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { connect } from 'umi'

type Props = {
    title: string,
    field: string,
    setItem: Function
}

function HeroUpload({ title, field, setItem }: Props) {
    // 上传
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(url);
                setItem(field, url)
            });
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    return (
        <div className={[style.dis, style.mb20].join(" ")}>
            <span className={[style.ml20, style.right].join(" ")}>
                { title }:
            </span>
            <div>
                <Upload
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    action="/api/upload/hero"
                    beforeUpload={beforeUpload}
                    onChange={handleChange}
                >
                    {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
            </div>
        </div>
    )
}

const mapStateToProps = (state: any) => {
    return {}
}

const mapDispatchToProps = (dispatch: Function) => {
    return {
        setItem(key: string, value: string) {
            dispatch({ type: "createHero/changeHeroItem", key, value })
        }
    }
}


export default connect(mapStateToProps, mapDispatchToProps)(HeroUpload)